package com.ioc.trade.config.redis;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * redis 数据操作：
 */
@Component
public class CacheProvider {

    @Resource
    private ZSetOperations<String, String> zSetOperations;

    @Autowired
    static  RedisTemplate<String,String> template;
    //由于当前class不在spring boot框架内（不在web项目中）所以无法使用autowired，使用此种方法进行注入
    //private static RedisTemplate<String, String> template = (RedisTemplate<String, String>) SpringBeanUtil.getBean("redisTemplate");

    public static <T> boolean set(String key, T value) {
        Gson gson = new Gson();
        return set(key, gson.toJson(value));
    }

    public static boolean set(String key, String value, long validTime) {
        boolean result = template.execute((RedisCallback<Boolean>) connection -> {
            RedisSerializer<String> serializer = template.getStringSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
            connection.expire(serializer.serialize(key), validTime);
            return true;
        });
        return result;
    }

    public static <T> T get(String key, Class<T> clazz) {
        Gson gson = new Gson();
        return gson.fromJson(get(key), clazz);
    }

    public static String get(String key) {
        String result = template.execute((RedisCallback<String>) connection -> {
            RedisSerializer<String> serializer = template.getStringSerializer();
            byte[] value = connection.get(serializer.serialize(key));
            return serializer.deserialize(value);
        });
        return result;
    }

    public static boolean del(String key) {
        return template.delete(key);
    }

//    /**
//     * redis 有序集合生成自增商户编号：
//     * DOUBLE :15位：
//     *
//     * @return
//     */
//    public static Double getMerchantNo(String agentNo) {
//        Optional<Long> agentNoSource = Optional.ofNullable(zSetOperations.rank(AgentDict.AGENT_MERCHANT_NO, agentNo));
//
//        if (!agentNoSource.isPresent()) {
//            zSetOperations.add(AgentDict.AGENT_MERCHANT_NO, agentNo, 1.0);
//        }
//        zSetOperations.incrementScore(AgentDict.AGENT_MERCHANT_NO, agentNo, 1);
//        return zSetOperations.score(AgentDict.AGENT_MERCHANT_NO, agentNo);
//    }


}
